package com.cplatform.cat;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        for (int i = 2; i < 6; i++) {
            ListNode newNode = new ListNode(i);
            if(head == null){
                head = newNode;
                return;
            }
            //每次使用temp副本接受
            ListNode temp = head;
            //迭代出链表尾
            while(temp.next != null){
                temp = temp.next;
            }
            //使用尾指向新的节点
            temp.next = newNode;
        }
        System.out.println(head);
        System.out.println(reverseList(head));

    }

    public static ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
    public static class ListNode {
        ListNode last;
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            List<Integer> result = new ArrayList<>();
            result.add(val);
            ListNode curr = this;
            while (curr != null && curr.next != null) {
                curr = curr.next;
                result.add(curr.val);
            }
            return result.toString();
        }
    }

}
